package com.dy.yunying.biz.service.datacenter.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.constant.OsEnum;
import com.dy.yunying.api.dto.ConversionAnalysisDto;
import com.dy.yunying.api.entity.ChannelManageDO;
import com.dy.yunying.api.entity.ParentGameDO;
import com.dy.yunying.api.entity.WanGameDO;
import com.dy.yunying.api.vo.ConversionAnalysisVo;
import com.dy.yunying.biz.dao.datacenter.impl.ConversionAnalysisDao;
import com.dy.yunying.biz.dao.manage.ChannelManageDOMapper;
import com.dy.yunying.biz.dao.manage.ParentGameDOMapper;
import com.dy.yunying.biz.dao.manage.WanGameDOMapper;
import com.dy.yunying.biz.service.datacenter.ConversionAnalysisService;
import com.dy.yunying.biz.service.manage.AdRoleUserService;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author chengang
 * @Date 2022/2/28
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ConversionAnalysisServiceImpl implements ConversionAnalysisService {

	private final AdRoleUserService roleUserService;

	private final ConversionAnalysisDao conversionAnalysisDao;

	private final ChannelManageDOMapper channelManageDOMapper;

	private final WanGameDOMapper wanGameDOMapper;

	private final ParentGameDOMapper parentGameDOMapper;


	/**
	 * 获取转化分析报表总数
	 * @param analysisDto
	 * @return
	 */
	@Override
	public int count(ConversionAnalysisDto analysisDto) {
		this.requireConversionQueryBean(analysisDto);
		if (!analysisDto.getIsAdmin() && analysisDto.getPrvInvestorIds().isEmpty()) {
			return 0;
		}
		return conversionAnalysisDao.selectConversionCount(analysisDto);
	}

	/**
	 * 分页转化分析报表
	 * @param analysisDto 查询条件
	 * @param isPage 是否分页
	 * @return
	 */
	@Override
	public List<ConversionAnalysisVo> page(ConversionAnalysisDto analysisDto, boolean isPage) {
		this.requireConversionQueryBean(analysisDto);
		if (!analysisDto.getIsAdmin() && analysisDto.getPrvInvestorIds().isEmpty()) {
			return Collections.emptyList();
		}
		final List<ConversionAnalysisVo> list = conversionAnalysisDao.selectConversionPage(analysisDto, isPage);
		// 填充主渠道名称和子游戏名称字段
		this.convertConversionDataList(analysisDto, list);
		return list;
	}

	private void requireConversionQueryBean(ConversionAnalysisDto analysisDto) {
		// 判断当前用户是否为系统管理员
		analysisDto.setIsAdmin(SecurityUtils.getRoles().contains(1));

		// 当前账号及管理的账号
		if (!analysisDto.getIsAdmin()) {
			Set<Long> prvInvestorIds = new HashSet<>();
			prvInvestorIds.add(Integer.toUnsignedLong(SecurityUtils.getUser().getId()));
			prvInvestorIds.addAll(Optional.ofNullable(roleUserService.getOwnerRoleUserIds()).map(Collection::stream).map(e -> e.map(Integer::toUnsignedLong).collect(Collectors.toList())).orElse(Collections.emptyList()));
			analysisDto.setPrvInvestorIds(prvInvestorIds);
		}
	}

	private void convertConversionDataList(ConversionAnalysisDto analysisDto, List<ConversionAnalysisVo> list) {
		final List<String> groupBys = analysisDto.getGroupBys();

		// 填充主渠道名称
		if (groupBys.contains("parentchl")) {
			final List<String> codeList = list.stream().map(ConversionAnalysisVo::getParentchl).distinct().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
			if (!codeList.isEmpty()) {
				final LambdaQueryWrapper<ChannelManageDO> queryWrapper = Wrappers.<ChannelManageDO>lambdaQuery().select(ChannelManageDO::getChncode, ChannelManageDO::getChnname).in(ChannelManageDO::getChncode, codeList).eq(ChannelManageDO::getPid, 0).eq(ChannelManageDO::getIsdelete, 0);
				final Map<String, String> parentchlMap = channelManageDOMapper.selectList(queryWrapper).stream().collect(Collectors.toMap(ChannelManageDO::getChncode, ChannelManageDO::getChnname, (k1, k2) -> k1));
				list.forEach(e -> e.setParentchlName(parentchlMap.get(e.getParentchl())));
			}
		}

		// 填充主游戏名称
		if (groupBys.contains("pgid")) {
			final List<Long> codeList = list.stream().map(ConversionAnalysisVo::getPgid).distinct().filter(Objects::nonNull).collect(Collectors.toList());
			final Map<Long, String> mapping = codeList.isEmpty() ? Collections.emptyMap() : parentGameDOMapper.selectList(Wrappers.<ParentGameDO>lambdaQuery().select(ParentGameDO::getId, ParentGameDO::getGname).in(ParentGameDO::getId, codeList)).stream().collect(Collectors.toMap(ParentGameDO::getId, ParentGameDO::getGname, (k1, k2) -> k1));
			list.forEach(e -> e.setPgname(StringUtils.defaultIfBlank(mapping.get(e.getPgid()), "-")));
		}

		// 填充子游戏名称
		if (groupBys.contains("gameid")) {
			final List<Long> gameidList = list.stream().map(ConversionAnalysisVo::getGameid).distinct().filter(Objects::nonNull).collect(Collectors.toList());
			if (!gameidList.isEmpty()) {
				final LambdaQueryWrapper<WanGameDO> queryWrapper = Wrappers.<WanGameDO>lambdaQuery().select(WanGameDO::getId, WanGameDO::getGname).in(WanGameDO::getId, gameidList).eq(WanGameDO::getIsdelete, 0);
				final Map<Long, String> gameMap = wanGameDOMapper.selectList(queryWrapper).stream().collect(Collectors.toMap(WanGameDO::getId, WanGameDO::getGname, (k1, k2) -> k1));
				list.forEach(e -> e.setGname(gameMap.get(e.getGameid())));
			}
		}

		// 填充系统名称
		if (groupBys.contains("os")) {
			list.forEach(e -> e.setOsName(OsEnum.getName(e.getOs())));
		}
	}
}
